package club.banyuan.reserve.service;

import club.banyuan.reserve.config.JwtUtils;
import club.banyuan.reserve.mapper.UserMapper;
import club.banyuan.reserve.mapper.UserRoleRelMapper;
import club.banyuan.reserve.model.User;
import club.banyuan.reserve.model.UserExample;
import club.banyuan.reserve.model.UserRoleRel;
import cn.hutool.crypto.digest.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author HanChao
 * 描述信息：
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleRelMapper userRoleRelMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public User userLogin(String username, String password) {

        // 判断用户是否存在
        UserExample example = new UserExample();
        example.createCriteria()
                .andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(example);

        if (userList.size() == 0) {

            return null;
        }
        User user = userList.get(0);

        return user;
    }

    @Override
    public boolean userRegister(String username, String password) {

        // 判断用户名是否已经存在
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(example);

        if (!CollectionUtils.isEmpty(userList)) {

            User user1 = userList.get(0);

            if (user1.getUsername().equals(username)) {

                return false;
            }
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(BCrypt.hashpw(password));  // BCry加密
        user.setNickname("测试");

        userMapper.insertSelective(user);

        // 取出userId
        UserExample example1 = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<User> userList1 = userMapper.selectByExample(example);
        User user1 = userList1.get(0);
        int userId = user1.getId();

        UserRoleRel userRoleRel = new UserRoleRel();
        userRoleRel.setRoleId(2);
        userRoleRel.setUserId(userId);
        userRoleRelMapper.insertSelective(userRoleRel);

        return true;
    }
}
